package com.stephen.jsbridge.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by stephen on 2016/4/26.
 */
public class StephenToolUtils {
    public static final int req_ActivitySelectContact = 6789;
    public static boolean StephenLogSwitch = true;
    public static String MasterColorHex = "#0eb594",MasterFontColorHex = "#ffffff";
    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    public static void LogD(String logMsg){
        if(StephenLogSwitch) Log.d("StephenLog",logMsg);
    }

    public static int strInStringArray(String a, String[] b) {
        if(TextUtils.isEmpty(a) || null == b)return -1;
        for (int i = 0; i < b.length; i++){
            if(a.equals(b[i]))return i;
        }//end of for
        return -1;
    }

    public static void showShortHintInfo(Context context, String text){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    public static void showLongHintInfo(Context context, String text){
        Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }

    //删除文件夹
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            (new File(folderPath.toString())).delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if(!file.exists())return flag;
        if(!file.isDirectory())return flag;
        String[] tempList = file.list();
        File temp = null;
        for(int i = 0; i < tempList.length; i++){
            if(path.endsWith(File.separator)){
                temp = new File(path + tempList[i]);
            }else{
                temp = new File(path + File.separator + tempList[i]);
            }
            if(temp.isFile())temp.delete();
            if(temp.isDirectory()){
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }//end of if
        }//end of for
        return flag;
    }

    public static void viewOrCreateDir(String dirPath) {
        File dir = new File(dirPath);
        if(!dir.exists())dir.mkdirs();
    }

    public static boolean viewAndDeleteDirOrFile(String filePath) {
        if(!TextUtils.isEmpty(filePath)){
            File dir = new File(filePath);
            if(dir.exists())return dir.delete();
        }//end of if
        return false;
    }

    public static boolean isHaveDirOrFile(String filePath) {
        if(!TextUtils.isEmpty(filePath)){
            File dir = new File(filePath);
            return dir.exists();
        }//end of if
        return false;
    }

    public static boolean isHaveSDCard(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))return true;
        return false;
    }

    public static String getSD_CardRootPath(){
        if(isHaveSDCard())return Environment.getExternalStorageDirectory().getAbsolutePath();
        return null;
    }

    public static Bitmap rotateBitmap(Bitmap bitmap, int angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }//end of if
        return inSampleSize;
    }

    public static Bitmap scaleBitmap(byte[] data, int newWidth, int newHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data,0,data.length,options);
        options.inSampleSize = calculateInSampleSize(options, newWidth, newHeight);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,data.length,options);
        return bitmap;
    }

    public static Bitmap scaleBitmap(Bitmap org, int newWidth, int newHeight) {
        if (null == org)return null;
        Matrix matrix = new Matrix();
        matrix.postScale((float) newWidth / org.getWidth(), (float) newHeight / org.getHeight());
        return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);
    }

    //bitmap转为base64
    public static String bitmapToBase64String(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (null != bitmap) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }//end of if
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.flush();
                    baos.close();
                }//end of if
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Drawable bitmapToDrawable(Bitmap bitmap) {
        return bitmap == null ? null : new BitmapDrawable(bitmap);
    }

    //以最省内存的方式读取本地资源的图片
    public static Bitmap getBitmapFromResId(Context context, int resId){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    //以最省内存的方式读取本地资源的图片
    public static Bitmap getBitmapForSDCard(String imagePath){
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.ARGB_4444;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        return BitmapFactory.decodeFile(imagePath, opt);
    }

    public static boolean saveBitmapToLocal(Bitmap bmp, int quality, String savePath) {
        if(null != bmp){
            try {
                File f = new File(savePath);
                if(f.exists())f.delete();
                FileOutputStream out = new FileOutputStream(f);
                bmp.compress(Bitmap.CompressFormat.PNG, (quality > 0 && quality <=100) ? quality : 100, out);
                out.flush();
                out.close();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }//end of if
        return false;
    }

    public static boolean copyAssetFiles(Context context, String assetFolderName, File outDir){
        try{
            AssetManager assetManager = context.getAssets();
            String[] fileAry = assetManager.list(assetFolderName);
            if(null != fileAry && fileAry.length > 0)for(String file : fileAry)copyAssetFile(context,assetFolderName,file,outDir);
            return true;
        }catch(IOException e){
            e.printStackTrace();
            return false;
        }
    }

    public static File copyAssetFile(Context context, String assetFilePath, String assetFileName, File outDir){
        try{
            File outFile = new File(outDir,assetFileName);
            if(!outFile.exists()){
                if(!outDir.exists())outDir.mkdirs();
                InputStream is;
                AssetManager assetManager = context.getAssets();
                if(TextUtils.isEmpty(assetFilePath)){
                    is = assetManager.open(assetFileName);
                }else{
                    is = assetManager.open(assetFilePath+ File.separator+assetFileName);
                }
                FileOutputStream out = new FileOutputStream(outFile);
                byte buf[] = new byte[1024];
                int len;
                while((len = is.read(buf)) > 0)out.write(buf, 0, len);
                out.close();
                is.close();
            }//end of if
            return outFile;
        }catch(IOException e){
            e.printStackTrace();
            return null;
        }
    }

    //btn selector
    public static StateListDrawable createSelector(String stateNormal, String statePressed, String stateFocused, String stateDisabled) {
        Drawable normal = stateNormal == null ? null : BitmapDrawable.createFromPath(stateNormal);
        Drawable pressed = statePressed == null ? null : BitmapDrawable.createFromPath(statePressed);
        Drawable focused = stateFocused == null ? null : BitmapDrawable.createFromPath(stateFocused);
        Drawable disabled = stateDisabled == null ? null : BitmapDrawable.createFromPath(stateDisabled);
        return createSelector(normal,pressed,focused,disabled);
    }

    //btn selector
    public static StateListDrawable createSelector(Drawable normal, Drawable pressed, Drawable focused, Drawable disabled) {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[] {android.R.attr.state_pressed,android.R.attr.state_enabled }, pressed);
        stateListDrawable.addState(new int[] {android.R.attr.state_enabled,android.R.attr.state_focused }, focused);
        stateListDrawable.addState(new int[] {android.R.attr.state_focused }, focused);
        stateListDrawable.addState(new int[] {android.R.attr.state_enabled }, normal);
        stateListDrawable.addState(new int[] {android.R.attr.state_window_focused }, disabled);
        stateListDrawable.addState(new int[] {},normal);
        return stateListDrawable;
    }

    //checkbox/radio selector(warning:state_enabled below for state_checked)
    public static StateListDrawable createSelector(Drawable normal, Drawable checked) {
        StateListDrawable stateListDrawable = new StateListDrawable();
        stateListDrawable.addState(new int[] {android.R.attr.state_checked}, checked);
        stateListDrawable.addState(new int[] {android.R.attr.state_enabled}, normal);
        return stateListDrawable;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static Point getScreenWHToPoint(Activity context){
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new Point(dm.widthPixels,dm.heightPixels);
    }

    public static boolean isShouldHideKeyboard(View view, MotionEvent event) {
        if(null != view && (view instanceof EditText)){
            int[] location = {0, 0};
            view.getLocationInWindow(location);
            int left = location[0],top = location[1],bottom = top + view.getHeight(),right = left + view.getWidth();
            if(event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom){
                return false;
            }else{
                return true;
            }
        }//end of if
        return false;
    }

    //获取视图中根布局并转换成ViewGroup
    public static ViewGroup convertRootViewToViewGroup(View mainView){
        if(null != mainView.getRootView() && mainView.getRootView() instanceof ViewGroup){
            return (ViewGroup)mainView.getRootView();//ViewGroup subclass AbsoluteLayout, AdapterView, FrameLayout, LinearLayout, RelativeLayout, SlidingDrawer
        }//end of if
        return null;
    }

    //得到子控件在父布局中的索引
    public static int getChildViewInRootViewIndex(ViewGroup rootView, View mainView, int findViewId){
        if(null == rootView)rootView = convertRootViewToViewGroup(mainView);
        if(null != rootView){
            for(int i = 0;i < rootView.getChildCount();i++){
                View childView = rootView.getChildAt(i);
                if(null != childView && findViewId == childView.getId())return i;
            }//end of for
        }//end of if
        return -1;
    }

    //设置TextView环绕图片(direction value is 1/left,2/top,3/right,4/bottom)
    public static void setTextViewAroundDrawable(Context context, TextView textView, int imgResId, int imgWidthDp, int imgHeightDp, int imgPaddingDp, int direction) {
        setTextViewAroundDrawable(context,textView,context.getResources().getDrawable(imgResId),imgWidthDp,imgHeightDp,imgPaddingDp,direction);
    }
    public static void setTextViewAroundDrawable(Context context, TextView textView, Drawable aroundDrawable, int imgWidthDp, int imgHeightDp, int imgPaddingDp, int direction){
        if(null != textView && null != aroundDrawable){
            aroundDrawable.setBounds(0,0, dip2px(context,imgWidthDp),dip2px(context,imgHeightDp));
            textView.setCompoundDrawablePadding(dip2px(context,imgPaddingDp));
            switch(direction){
                case Gravity.LEFT:
                    textView.setCompoundDrawables(aroundDrawable, null, null, null);
                    break;
                case Gravity.TOP:
                    textView.setCompoundDrawables(null, aroundDrawable, null, null);
                    break;
                case Gravity.RIGHT:
                    textView.setCompoundDrawables(null, null, aroundDrawable, null);
                    break;
                case Gravity.BOTTOM:
                    textView.setCompoundDrawables(null, null, null, aroundDrawable);
                    break;
            }//end of switch
        }//edn of if
    }

    public static int generateViewId() {
        for(;;){
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1;//Roll over to 1, not 0.
            if(sNextGeneratedId.compareAndSet(result, newValue))return result;
        }//end of for
    }

    public static void setBackgroundAllVersion(Context context, View view, int bgResId){
        setBackgroundAllVersion(view,context.getResources().getDrawable(bgResId));
    }

    public static void setBackgroundAllVersion(View view, Drawable bgDrawable){
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
            view.setBackground(bgDrawable);
        }else{
            view.setBackgroundDrawable(bgDrawable);
        }
    }

    //格式化字符串
    public static String formatStr(String format, int args) {
        return String.format(format, args);
    }

    public static Point getScreenSize(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point(wm.getDefaultDisplay().getWidth(), wm.getDefaultDisplay().getHeight());
        return point;
    }

    /*public static void setFullSpan(StaggeredGridLayoutManager.LayoutParams layoutParams) {
        if(layoutParams != null && !layoutParams.isFullSpan())layoutParams.setFullSpan(true);
    }*/

    public static void removeViewFromParent(View view) {
        if(view == null)return;
        ViewParent parent = view.getParent();
        if(parent != null)((ViewGroup) parent).removeView(view);
    }

    public static void callPhoneNumber(Activity activity, String phone_number){
        if(!TextUtils.isEmpty(phone_number)){
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+phone_number));
            activity.startActivity(intent);//内部类
        }else{
            showShortHintInfo(activity,"抱歉,不能完成拨号,号码为空!");
        }
    }

    public static void callSelectContact(Activity activity){
        activity.startActivityForResult(new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI), req_ActivitySelectContact);
    }

    public static boolean isAppRunning(Context context){
        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        for(ActivityManager.RunningAppProcessInfo appProcess : appProcesses)if(appProcess.processName.equals(context.getPackageName()))return true;
        return false;
    }

    //把图片插入到系统图库并刷新相册
    public static void insertSystemPhotoAlbumScan(Context context, boolean insertSystemAlbum, String photoName, String photoPath){
        if(insertSystemAlbum){
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(), photoPath, photoName, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }//end of if
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + photoPath)));//通知图库更新
    }

    //发送广播删除相册缩略图
    public static void deleteSystemPhotoAlbumByScan(Context ctx, String filePath) {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(filePath)));
        ctx.sendBroadcast(scanIntent);
    }

    //删除相册缩略图
    public static void deleteSystemPhotoAlbum(Context ctx, String filePath){
        ctx.getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[]{filePath});
    }

    public static PointF getScreenWidthHeightPixels(Context context){
        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        return new PointF(dm.widthPixels,dm.heightPixels);
    }

    public static PointF getScreenWidthHeightPixels(Activity activity){
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new PointF(dm.widthPixels,dm.heightPixels);
    }

    public static boolean checkCurRunningIsPad(Context context){//smallestScreenWidth >= 600px is pad
        return context.getResources().getConfiguration().smallestScreenWidthDp >= 600;
    }

    public static boolean copyTextToClipboard(Context context, String str){
        ClipboardManager cm = (ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE);
        if(null != cm){
            cm.setText(str);
            return true;
        }//end of if
        return false;
    }

    public static void openUrlForBrowser(Context context, String url){
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        context.startActivity(intent);
    }
}
